# coding=utf-8

from flask import Blueprint, request, jsonify, json, make_response, redirect, g
from common.models.OauthCustomerBind import OauthCustomerBind
from common.models.Customer import Customer
from common.libs.customer.CustomerLibs import CustomerLibs
from common.libs.Helper import  get_current_time
from common.libs.UrlManager import UrlManager
from application import app,db
from web.controllers.BaseControllerHelper import *
from .Helper import *

route_api_customer = Blueprint( 'customer_page',__name__ )

@route_api_customer.route("/login", methods=["POST"])
def login():
    resp = gene_response(msg="OK")
    data = request.json["user_info"]
    print(data)
    code = get_values_by_request(data, "code")
    if not code or len(code) < 1:
        resp = gene_response(code=-1, msg="需要code", data=[])
        return jsonify(resp)
    #换取open_id
    open_id = CustomerLibs.getWeChatOpenId(code)
    if open_id is None:
        resp = gene_response(code=-1, msg="调用微信出错", data=[])
        return jsonify(resp)

    nickname = get_values_by_request(data, "nickName")
    sex = get_values_by_request(data, "gender")
    avatar = get_values_by_request(data, "avatarUrl")

    bind_info = OauthCustomerBind.query.filter_by( open_id = open_id,type = 1 ).first()
    if not bind_info:
        customer_model = Customer()
        customer_model.nickname = nickname
        customer_model.sex = sex
        customer_model.avatar = avatar
        customer_model.salt = CustomerLibs.geneSalt()
        customer_model.updated_time = get_current_time()
        customer_model.created_time = get_current_time()
        db.session.add(customer_model)
        db.session.commit()

        bind_model = OauthCustomerBind()
        bind_model.c_id = customer_model.id
        bind_model.type = 1
        bind_model.open_id = open_id
        bind_model.extra = ''
        bind_model.updated_time = get_current_time()
        bind_model.created_time = get_current_time()
        db.session.add(bind_model)
        db.session.commit()

        bind_info = bind_model
    customer_info = Customer.query.filter_by( id=bind_info.c_id ).first()
    token = "%s#%s" % (CustomerLibs.geneAuthCode(customer_info), customer_info.id)
    resp = gene_response(code=200, msg="OK", data={'token': token, "user_info" : data})
    return jsonify(resp)